<?php

declare(strict_types=1);

namespace core;

class Controller
{

    // url 解析后获得的数据
    public $gets = [];

    // 核心数据表名
    public $table = null;

    // 数据表主键
    public $primaryKey = null;

    // 数据表操作对象
    public $db;

    // 数据排序规则
    public $order = null;

    // 网页信息 array(页面标题, 页面关键字, 页面描述)
    public $pageInfo = [
        'title'       => '',
        'keywords'    => '',
        'description' => '',
    ];

    // 缓存对象
    protected $cacher = null;

    // 缓存名称
    protected $cacheName;

    // 初始化函数
    public function __init()
    {
        if ($this->table != null) {
            $this->db = db($this->table);
        }

        $this->requestFilter();
    }

    // 过滤请求数据
    private function requestFilter()
    {
        // 过滤 $_POST
        if (!empty($_POST)) {
            foreach ($_POST as $k => $v) {
                $_POST[$k] = trim(escape($v));
            }
        }

        // 过滤 $_GET
        if (!empty($_GET)) {
            foreach ($_GET as $k => $v) {
                $_GET[$k] = trim(escape($v));
            }
        }

        // 过滤网站参数
        if (!empty($this->gets)) {
            foreach ($this->gets as $k => $v) {
                $this->gets[$k] = trim(escape($v));
            }
        }

    }

    // 视图展示
    public function view(string $tplName)
    {
        $file = VIEW_PATH . $tplName . '.view.php';
        // $tplUrl = is_null($tplName) ? $this->viewDir . CONTROLLER_NAME . '/' . METHOD_NAME . '.view.php' : $this->viewDir . $tplName;

        if (!file_exists($file)) {
            throw new \Exception("模板文件 {$tplName} 不存在");
        }

        ob_start();
        include($file);
        $contents = ob_get_contents() ?: '';
        ob_end_flush();

        return $contents;
        
    }

    // 语言包设置
    // protected function setLang($langType)
    // {
    //     pgSetCookie('phpGraceLang', $langType);
    // }

    // 获取数据列表 
    protected function dataList(int $everyPagerNum = 20, $fields = '*')
    {
        if ($this->order === null) {
            $this->order = $this->primaryKey . ' desc';
        }
        $arr = $this->db->page($everyPagerNum)->order($this->order)->fetchAll($fields);
        $this->pager = $arr[1];
        return $arr[0];
    }

    // 利用 id 获取一条数据
    protected function getDataById()
    {
        if (empty($this->gets[0])) {
            return null;
        }
        return $this->db->where( $this->primaryKey . ' = ?', [intval($this->gets[0])] )->first();
    }

    // 获取一条数据并以默认值形式复制给对应表单元素 
    protected function getDefaultVal(array $exception = [])
    {
        if (empty($this->gets[0])) {
            return null;
        }

        $data = $this->db->where($this->primaryKey . ' = ?', array(intval($this->gets[0])))->first();

        $jsonPreData = [];
        
        if (!empty($exception) && !is_array($exception)) {
            $exception = explode(',', $exception);
        }
        foreach ($data as $k => $v) {
            if (!in_array($k, $exception)) {
                $jsonPreData[$k] = $data[$k];
            }
        }
        echo '<script>$(function(){';
        echo 'var dataobject = ' . json_encode($jsonPreData) . ';';
        if ($data) {
            foreach ($data as $k => $v) {
                if (!in_array($k, $exception)) {
                    echo '$("input[name=' . $k . ']").val(dataobject.' . $k . ');';
                }
            }
        }
        echo '});</script>';
        return $data;
    }

    // 获取缓存对象
    // protected function getCacher()
    // {
    //     if (!empty($this->cacher)) {
    //         return null;
    //     }
    //     $config         = sc('cache');
    //     if (empty($config)) {
    //         throw new graceException('缓存设置错误', 100009);
    //     }
    //     if (!in_array($config['type'], sc('allowCacheType'))) {
    //         throw new graceException('缓存类型错误', 100010);
    //     }
    //     $type           = strtolower($config['type']);
    //     $className      = 'phpGrace\\tools\\caches\\' . $type . 'Cacher';
    //     $this->cacher   = $className::getInstance($config);
    // }

    // 进行缓存工作
    // protected function cache($name, $id = null, $queryMethod, $timer = 3600, $isSuper = true)
    // {
    //     if (PG_CLOSE_CACHE) {
    //         $queryRes    = $this->$queryMethod();
    //         $this->$name = $queryRes;
    //         return false;
    //     }
    //     $this->getCacher();
    //     $this->cacheName = graceCacheName($name, $id, $isSuper);
    //     $cachedRes = $this->cacher->get($this->cacheName);
    //     if ($cachedRes) {
    //         $this->$name = $cachedRes;
    //         return true;
    //     }
    //     $queryRes = $this->$queryMethod();
    //     $this->cacher->set($this->cacheName, $queryRes, $timer);
    //     $this->$name = $queryRes;
    // }

    // 清除全部缓存
    // public function clearCache()
    // {
    //     $this->getCacher();
    //     $this->cacher->clearCache();
    // }

    // 清除指定缓存
    // public function removeCache($name, $id = null, $isSuper = true)
    // {
    //     $this->getCacher();
    //     $name = graceCacheName($name, $id, $isSuper);
    //     $this->cacher->removeCache($name);
    // }

    // 初始化 gets 数据
    // 如果某个指定的数据为空则进行定义及赋值
    protected function initVal($key, $val = '')
    {
        if (empty($this->gets[$key])) {
            $this->gets[$key] = $val;
        }
    }

    // 将 gets 指定数据整数化
    protected function intVal($key, $val = 0)
    {
        if (empty($this->gets[$key])) {
            $this->gets[$key] = 0;
        } else {
            $this->gets[$key] = intval($this->gets[$key]);
        }
    }
}
